package com.csair.platform.cit.service.biz.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.csair.invoice.common.base.util.BeanUtils;
import com.csair.invoice.common.base.util.CastUtil;
import com.csair.invoice.common.base.util.StringUtil;
import com.csair.invoice.common.base.util.collection.CollectionUtil;
import com.csair.invoice.common.base.vo.JsonResult;
import com.csair.platform.cit.facade.exception.CitBizException;
import com.csair.platform.cit.facade.model.CitQueryParam;
import com.csair.platform.cit.facade.model.CitSendParam;
import com.csair.platform.cit.facade.model.a202000.CitFzjgFormVo;
import com.csair.platform.cit.facade.model.a202000.CitZjgxxFormVo;
import com.csair.platform.cit.service.biz.IA202000Service;
import com.csair.platform.cit.service.dao.a200000.CitSbbxxRepository;
import com.csair.platform.cit.service.dao.a202000.CitFzjgFormRepository;
import com.csair.platform.cit.service.dao.a202000.CitFzjgRepository;
import com.csair.platform.cit.service.dao.a202000.CitZjgxxFormRepository;
import com.csair.platform.cit.service.entity.CitDeclareRecord;
import com.csair.platform.cit.service.entity.CitFzjg;
import com.csair.platform.cit.service.entity.CitFzjgForm;
import com.csair.platform.cit.service.entity.CitSbbxx;
import com.csair.platform.cit.service.entity.CitZjgxxForm;
import com.csair.platform.usercenter.facade.model.user.UserVo;

import lombok.extern.slf4j.Slf4j;

/**
 * [分配表数据]服务实现类
 * @author ：caoyu
 * 
 */
@Slf4j
@Service
public class A202000ServiceImpl extends InitBaseServiceImpl implements IA202000Service {
    
    /**
     * 分配表的总机构信息dao
     */
    @Autowired
    CitZjgxxFormRepository zjgxxFormDao;
    
    /**
     * 分配表的分支机构信息dao
     */
    @Autowired
    CitFzjgFormRepository fzjgFormDao;
    
    /**
     * 分支机构信息dao
     */
    @Autowired
    CitFzjgRepository fzjgDao;
    
    /**
     * 申报表信息dao
     */
    @Autowired
    CitSbbxxRepository sbbxxDao;
    
    /**
     * 获取A202000，分配表的期初数据
     * @param param 查询参数
     * @param user 当前用户
     * @Param isJson 是否返回JSON字符串
     * @return  JSONObject.put("zjgxx", CitZjgxxFormVo)
     *          JSONObject.put("fzjgxx", List<CitFzjgFormVo>)
     */
    @Override
    public JsonResult<JSONObject> getInitData(CitQueryParam param, UserVo user, boolean isJson) {
        JSONObject result = new JSONObject();
        String returnStr = getInitJsonData(param, user);
        if (StringUtil.isEmpty(returnStr)) {
            throw new CitBizException(CitBizException.SEND_ERROR, "调用税局接口异常");
        }
        JSONObject head = JSON.parseObject(returnStr).getJSONObject("head");
        String headErrorCode = head.getString("errorCode");
        if (!"0".equals(headErrorCode)) {
            String headErrorMsg = head.getString("errorMsg");
            throw new CitBizException(CastUtil.castInt(headErrorCode), headErrorMsg);
        }
        JSONObject dataResult = JSON.parseObject(returnStr);
        String bodyStr = dataResult.getString("body"); 
        JSONObject dataBody = JSON.parseObject(bodyStr); 
        String returnFlagStr = dataBody.getString("returnFlag"); 
        if (!"Y".equals(returnFlagStr)) {
            String errInfoStr = dataBody.getString("errInfo");
            JSONObject dataErrInfo = JSON.parseObject(errInfoStr); 
            String errorMsg = dataErrInfo.getString("msg");
            throw new CitBizException(CitBizException.GET_INIT_DATA_ERROR, errorMsg);
        }
        String body2Str = dataBody.getString("body"); 
        JSONObject dataBody2 = JSON.parseObject(body2Str); 
        //==================总机构信息==================
        String htStr = dataBody2.getString("ht_"); 
        JSONObject dataHt = JSON.parseObject(htStr); 
        String ywbwStr = dataHt.getString("ywbw"); 
        JSONObject dataYwbw = JSON.parseObject(ywbwStr); 
        String a202000YwbdStr = dataYwbw.getString("A202000Ywbd"); 
        JSONObject dataA202000Ywbd = JSON.parseObject(a202000YwbdStr); 
        String zjgxxFormStr = dataA202000Ywbd.getString("zjgxxForm"); 
        JSONObject objectZjgxxForm = JSON.parseObject(zjgxxFormStr); 
        CitZjgxxFormVo zigxxFormVo = new CitZjgxxFormVo();
        if (objectZjgxxForm != null) {
            //zigxxFormVo.setZjgmc(objectZjgxxForm.getString("zjgmc"));
            //zigxxFormVo.setZjgnsrsbh(objectZjgxxForm.getString("zjgnsrsbh"));
            zigxxFormVo.setYnsdse(objectZjgxxForm.getString("ynsdse")); //应纳所得税额
            zigxxFormVo.setZjgftsdse(objectZjgxxForm.getString("zjgftsdse")); //总机构分摊所得税额
            zigxxFormVo.setZjgczjzfpsdse(objectZjgxxForm.getString("zjgczjzfpsdse")); //总机构财政集中分配所得税额
            zigxxFormVo.setFzjgftdsdse(objectZjgxxForm.getString("fzjgftdsdse")); //分支机构分摊的所得税额
        }
        String fqStr = dataBody2.getString("fq_"); 
        JSONObject dataFq = JSON.parseObject(fqStr); 
        String zjgxxStr = dataFq.getString("zjgxx"); 
        JSONObject objectZjgxx = JSON.parseObject(zjgxxStr); 
        if (objectZjgxx != null) {
            zigxxFormVo.setZjgmc(objectZjgxx.getString("zjgmc")); //总机构名称
            zigxxFormVo.setZjgnsrsbh(objectZjgxx.getString("zjgnsrsbh")); //总机构纳税人识别号
        }
        if (isJson) {
            result.put("zjgxx", JSON.toJSONString(zigxxFormVo));
        } else {
            result.put("zjgxx", zigxxFormVo);
        }
        //==================分支机构信息==================
        String hqStr = dataBody2.getString("hq_"); 
        JSONObject dataHq = JSON.parseObject(hqStr); 
        String fzjgxxGridStr = dataHq.getString("fzjgxxGrid"); 
        JSONObject dataFzjgxxGrid = JSON.parseObject(fzjgxxGridStr); 
        JSONArray data = dataFzjgxxGrid.getJSONArray("fzjgxxGridlb");  
        List<CitFzjgFormVo> listFzjg = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(data)) {
            for (int i = 0 ; i < data.size() ; i++) {
                JSONObject object = data.getJSONObject(i);
                CitFzjgFormVo entity = new CitFzjgFormVo();
                entity.setFzjgnsrsbh(object.getString("fzjgnsrsbh")); //纳税人识别号
                entity.setFzjgmc(object.getString("fzjgmc")); //分支机构名称
                entity.setZgswjgDm(object.getString("zgswjgdm")); //分支机构税务机关代码
                entity.setZgswjgmc(object.getString("zgswjgmc")); //分支机构税务机关名称
                entity.setFzjgsrze(object.getString("fzjgsrze")); //营业收入
                entity.setFzjggzze(object.getString("fzjggzze")); //职工薪酬
                entity.setFzjgzcze(object.getString("fzjgzcze")); //资产总额
                entity.setFpbl(object.getString("fpbl")); //分配比例
                entity.setSfxsdfjm(object.getString("sfxsdfjm")); //是否享受地方减免
                entity.setXsdfjmfd(object.getString("xsdfjmfd")); //享受民族地方减免幅度
                entity.setXsdfjmje(object.getString("xsdfjmje")); //享受民族地方优惠金额
                entity.setFzjgfpse(object.getString("fpse")); //分配所得税额
                listFzjg.add(entity);
            }
        }
        if (isJson) {
            result.put("fzjgxx", JSON.toJSONString(listFzjg));
        } else {
            result.put("fzjgxx", listFzjg);
        }
        log.info("返回前端的[分支机构所得税分配表]为：" + result.toString());
        return JsonResult.success(result);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void saveData(CitZjgxxFormVo zjgxxFormVo, List<CitFzjgFormVo> fzjgxxFormVo) {
        if (StringUtil.isEmpty(zjgxxFormVo.getZjgnsrsbh())) {
            throw new CitBizException(CitBizException.NSRSBH_NOT_NULL, "税号不能为空");
        }    
        //获取申报进度
        CitSendParam param = new CitSendParam();
        BeanUtils.copyProperties(zjgxxFormVo, param);
        param.setNsrsbh(zjgxxFormVo.getZjgnsrsbh());
        CitDeclareRecord record = this.queryDeclareRecord(param);
        if (record != null) {
            throw new CitBizException(CitBizException.NO_UPDATE_AFTER_DECLARATION, "该数据已进行了申报，禁止更新");
        }
        //先删除
        List<CitZjgxxForm> listZjg = this.queryZjgxx(zjgxxFormVo.getZjgnsrsbh(), zjgxxFormVo.getSkssqq(), zjgxxFormVo.getSkssqz());
        if (CollectionUtil.isNotEmpty(listZjg)) {
            for (CitZjgxxForm entity : listZjg) {
                List<CitFzjgForm> listFzjg = this.queryFzjgxx(entity.getId());
                if (CollectionUtil.isNotEmpty(listFzjg)) {
                    int count = listFzjg.size();
                    fzjgFormDao.deleteAll(listFzjg);
                    log.info("删除[分配表的分支机构信息]" + count + "行成功。");
                }
            }
            zjgxxFormDao.deleteAll(listZjg);
            log.info("删除[分配表的总机构信息]成功。");
        }
        
        //再插入
        CitZjgxxForm zjgxx = new CitZjgxxForm();
        Map<String, Object> mapZjg = this.cleanThousandth(BeanUtils.object2Map(zjgxxFormVo));
        CitZjgxxFormVo voZjg = BeanUtils.map2Bean(mapZjg, CitZjgxxFormVo.class);        
        BeanUtils.copyProperties(voZjg, zjgxx);
        zjgxx.setId(null);
        zjgxx.setXsdfjmfd("0"); //享受地方减免幅度,默认传0
        zjgxxFormDao.save(zjgxx);
        log.info("保存[分配表的总机构信息]成功。");
        List<CitFzjgForm> list = new ArrayList<>();
        for(CitFzjgFormVo entity : fzjgxxFormVo) {
            CitFzjgForm fzjgxx = new CitFzjgForm();
            Map<String, Object> mapFzjg = this.cleanThousandth(BeanUtils.object2Map(entity));
            CitFzjgFormVo voFzjg = BeanUtils.map2Bean(mapFzjg, CitFzjgFormVo.class);        
            BeanUtils.copyProperties(voFzjg, fzjgxx);
            fzjgxx.setZjgxxFormId(zjgxx.getId());
            fzjgxx.setDjxh("0"); //分支机构登记序号,传0
            fzjgxx.setZgswjDm(""); //分支机构税务局代码,传空
            fzjgxx.setZgswjgmc(""); //分支机构税务机关名称,传空
            fzjgxx.setFzjglxlb(""); //分支机构类型类别,传空
            list.add(fzjgxx);
        }
        fzjgFormDao.saveAll(list);
        log.info("保存[分配表的分支机构信息]" + list.size() + "行成功。");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public JsonResult<JSONObject> query(CitQueryParam param, UserVo user, boolean isJson) {
        String taxNo = param.getNsrsbh();
        String skssqq = param.getSkssqq();
        String skssqz = param.getSkssqz();
        
        //1.分配表的总机构信息
        List<CitZjgxxForm> listZjgxx = this.queryZjgxx(taxNo, skssqq, skssqz);
        CitZjgxxForm entityZjg = new CitZjgxxForm();
        List<CitFzjgFormVo> listFzjgxxInit = new ArrayList<>();
        Map<String, Object> mapZjgxx = new HashMap<>();
        Map<String, CitFzjgFormVo> mapFzjgInit = new HashMap<>();
        BigDecimal totalFzjgsrze = BigDecimal.ZERO;
        BigDecimal totalFzjggzze = BigDecimal.ZERO;
        BigDecimal totalFzjzcze = BigDecimal.ZERO;
        if (CollectionUtil.isEmpty(listZjgxx)) { //该季度没数据，获取期初进行自动初始化
            listZjgxx = new ArrayList<>();
            JsonResult<JSONObject> dataInit = this.getInitData(param, user, true);       
            JSONObject dataJson = dataInit.getData().get(0);
            String zjgxxStr = dataJson.getString("zjgxx");
            mapZjgxx = BeanUtils.json2Map(zjgxxStr);
            CitZjgxxFormVo zjgxxVo = BeanUtils.map2Bean(mapZjgxx, CitZjgxxFormVo.class);
            JSONArray dataFzjgxx = dataJson.getJSONArray("fzjgxx");
            for (int i = 0 ; i < dataFzjgxx.size() ; i++) {
                JSONObject object = dataFzjgxx.getJSONObject(i);        
                Map<String, Object> mapFzjgxx = BeanUtils.json2Map(object.toJSONString());
                CitFzjgFormVo fzjgxxVo = BeanUtils.map2Bean(mapFzjgxx, CitFzjgFormVo.class);
                totalFzjgsrze = totalFzjgsrze.add(new BigDecimal(fzjgxxVo.getFzjgsrze())); //营业收入
                totalFzjggzze = totalFzjggzze.add(new BigDecimal(fzjgxxVo.getFzjggzze())); //职工薪酬
                totalFzjzcze = totalFzjzcze.add(new BigDecimal(fzjgxxVo.getFzjgzcze())); //资产总额
                listFzjgxxInit.add(fzjgxxVo);
            }
            mapFzjgInit = listFzjgxxInit.stream().collect(Collectors.toMap(CitFzjgFormVo::getFzjgnsrsbh, b -> b));
            entityZjg.setZjgmc(zjgxxVo.getZjgmc());
            entityZjg.setZjgnsrsbh(zjgxxVo.getZjgnsrsbh());
            entityZjg.setSkssqq(skssqq);
            entityZjg.setSkssqz(skssqz);
            listZjgxx.add(entityZjg);
            //CitZjgxxFormDao.saveAll(listZjgxx);
        }
        CitZjgxxForm zjgxx = listZjgxx.get(0);
        //2.分配表的分支机构信息
        List<CitFzjgForm> listFzjgxx = null;
        if (zjgxx.getId() != null) {
            listFzjgxx = this.queryFzjgxx(zjgxx.getId());
        }
        if (CollectionUtil.isEmpty(listFzjgxx)) { //该季度没有数据，进行自动初始化
            listFzjgxx = new ArrayList<>();
            int year = Integer.parseInt(skssqq.substring(0, 4));
            List<CitFzjg> listFzjg = this.queryFzjg(year);
            if (CollectionUtil.isEmpty(listFzjg)) { //该年度没有分支机构数据，进行自动初始化
                listFzjg = new ArrayList<>();
                for (CitFzjgFormVo fzjgInit : listFzjgxxInit) {
                    CitFzjg fzjg = new CitFzjg();
                    fzjg.setYear(year);
                    fzjg.setFzjgnsrsbh(fzjgInit.getFzjgnsrsbh());
                    fzjg.setFzjgmc(fzjgInit.getFzjgmc());
                    listFzjg.add(fzjg);
                }
                fzjgDao.saveAll(listFzjg);
                log.info("保存[分支机构信息]" + listFzjg.size() + "行成功。");
            }
            for (CitFzjg fzjg : listFzjg) {
                CitFzjgForm entity = new CitFzjgForm();
                entity.setFzjgnsrsbh(fzjg.getFzjgnsrsbh());
                entity.setFzjgmc(fzjg.getFzjgmc());
                entity.setZjgxxFormId(zjgxx.getId());
                //通过期初数据初始化
                CitFzjgFormVo fzjgxxInit = mapFzjgInit.get(fzjg.getFzjgnsrsbh());
                if (fzjgxxInit != null) {
                    BigDecimal fzjgsrze = new BigDecimal(fzjgxxInit.getFzjgsrze());
                    entity.setFzjgsrze(fzjgsrze + ""); //营业收入
                    BigDecimal fzjggzze = new BigDecimal(fzjgxxInit.getFzjggzze());
                    entity.setFzjggzze(fzjggzze + ""); //职工薪酬
                    BigDecimal fzjgzcze = new BigDecimal(fzjgxxInit.getFzjgzcze());
                    entity.setFzjgzcze(fzjgzcze + ""); //资产总额
                    BigDecimal fpbl = BigDecimal.ZERO;
                    if (totalFzjgsrze != BigDecimal.ZERO && totalFzjggzze != BigDecimal.ZERO && totalFzjzcze != BigDecimal.ZERO) {
                        fpbl = (fzjgsrze.divide(totalFzjgsrze, 10, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("0.35"))).
                                add(fzjggzze.divide(totalFzjggzze, 10, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("0.35"))).
                                add(fzjgzcze.divide(totalFzjzcze, 10, BigDecimal.ROUND_HALF_UP).multiply(new BigDecimal("0.3")))
                                .setScale(10, BigDecimal.ROUND_HALF_UP);
                    }
                    entity.setFpbl(fpbl + ""); //分配比例 = （该分支机构营业收入／各分支机构营业收入之和）×0.35+ （该分支机构职工薪酬／各分支机构职工薪酬之和）×0.35+（该分支机构资产总额／各分支机构资产总额之和）×0.30
                    entity.setFzjgfpse(fzjgxxInit.getFzjgfpse()); //分支机构分配税额
                    entity.setSfxsdfjm(fzjgxxInit.getSfxsdfjm()); //是否享受地方减免
                    entity.setXsdfjmfd(fzjgxxInit.getXsdfjmfd()); //享受地方减免金额
                    entity.setXsdfjmje(fzjgxxInit.getXsdfjmje()); //享受地方减免幅度
                }
                listFzjgxx.add(entity);
            }
            //CitFzjgFormDao.saveAll(listFzjgxx);
        }

        JSONObject result = new JSONObject();
        if (isJson) {
            result.put("zjgxx", JSON.toJSONString(zjgxx)); 
            result.put("fzjgxx", JSON.toJSONString(listFzjgxx));
        } else {
            result.put("zjgxx", zjgxx); 
            result.put("fzjgxx", listFzjgxx);
        }
        log.info("返回前端的[分配表数据]为：" + result.toString());
        return JsonResult.success(result);
    }

    /**
     * 获取[分配表的总机构信息]
     * @param taxNo 税号
     * @param skssqq 税款所属期起
     * @param skssqz 税款所属期止
     * @return [分配表的总机构信息]
     */
    @Override
    public List<CitZjgxxForm> queryZjgxx(String taxNo, String skssqq, String skssqz) {
        CitZjgxxForm query = new CitZjgxxForm();
        query.setZjgnsrsbh(taxNo);
        query.setSkssqq(skssqq);
        query.setSkssqz(skssqz);
        Example<CitZjgxxForm> example = Example.of(query);
        List<CitZjgxxForm> list = zjgxxFormDao.findAll(example);
        //从主表获取总机构3项金额
        CitSbbxx sbbxx = this.querySbbxxData(taxNo, skssqq, skssqz);
        if (sbbxx != null) {
            for (CitZjgxxForm zjgxx : list) {
                zjgxx.setYnsdse(sbbxx.getYbtsdseLj()); //应纳所得税额 =（A类）表16行数据
                zjgxx.setZjgftsdse(sbbxx.getZjgyftsdseBq()); //总机构分摊所得税额 =（A类）表18行数据
                zjgxx.setZjgczjzfpsdse(sbbxx.getCzjzfpsdseBq()); //总机构财政集中分配所得税额 =（A类）表19行数据
            }
        }
        return list;
    }

    /**
     * 获取[主表数据-申报表信息]
     * @param taxNo 税号
     * @param skssqq 税款所属期起
     * @param skssqz 税款所属期止
     * @return [主表数据-申报表信息]
     */
    private CitSbbxx querySbbxxData(String taxNo, String skssqq, String skssqz) {
        CitSbbxx query = new CitSbbxx();
        query.setNsrsbh(taxNo);
        query.setSkssqq(skssqq);
        query.setSkssqz(skssqz);
        Example<CitSbbxx> example = Example.of(query);
        List<CitSbbxx> list = sbbxxDao.findAll(example);    
        if (CollectionUtil.isNotEmpty(list)) {
            return list.get(0);
        }
        return null;
    }
    
    /**
     * 获取[分配表的分支机构信息]
     * @param zjgxxFormId 主机构id
     * @return [分配表的分支机构信息]
     */
    @Override
    public List<CitFzjgForm> queryFzjgxx(long zjgxxFormId) {
        CitFzjgForm query = new CitFzjgForm();
        query.setZjgxxFormId(zjgxxFormId);
        Example<CitFzjgForm> example = Example.of(query);
        return fzjgFormDao.findAll(example);
    }
    @Override
    public List<CitFzjg> queryFzjg(int year) {
        CitFzjg query = new CitFzjg();
        query.setYear(year);
        Example<CitFzjg> example = Example.of(query);
        return fzjgDao.findAll(example);
    }
}
